<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <title>Slay The Spire</title>
    <meta charset="UTF-8">
    <script src="https://cdn.bootcss.com/vue/2.5.9/vue.min.js"></script>
    <script src="https://cdn.bootcss.com/element-ui/2.0.7/index.js"></script>
    <link href="https://cdn.bootcss.com/element-ui/2.0.7/theme-chalk/index.css" rel="stylesheet">
    
    <script type="text/javascript">
        function xorBytes(bytes) {
            var key = document.getElementById("key").value;
            var keyLength = key.length;
            var keyBytes = new Uint8Array(keyLength);
            for (var i=0; i<keyLength; i++) {
                keyBytes[i] = key.charCodeAt(i);
            }

            var bytesLength = bytes.length;
            var xors = new Uint8Array(bytesLength);
            var j = 0;
            for (var i=0; i<bytesLength; i++) {
                xors[i] = bytes[i] ^ keyBytes[j++];
                if (j == keyLength) {
                    j = 0;
                }
            }

            return xors;
        }

        function onFileChange(files) {
            if (files.length) {
                var file = files[0];
                document.getElementById("filename").innerHTML = file.name;

                var reader = new FileReader();
                reader.readAsText(file);
                reader.onload = function() {
                    var decoded = window.atob(this.result);
                    var len = decoded.length;
                    var bytes = new Uint8Array(len);
                    for (var i=0; i<len; i++) {
                        var a = decoded.charCodeAt(i)
                        bytes[i] = a;
                    }
                    
                    var jsonBytes = xorBytes(bytes);
                    var jsonString = new TextDecoder("ascii").decode(jsonBytes);
                    var json = JSON.parse(jsonString);

                    document.getElementById("show").innerText = jsonString;

                    console.log(json);
                }
                reader.onerror = function() {
                    document.getElementById("show").innerText = reader.error.message;
                }
            }
        }

        function onDecode() {
            var a = document.getElementById("iFile");
            a.click();
        }

        function onEncode() {
        }
    </script>
</head>

<body>
    <span>KEY: </span>
    <input type="text" value="key" id="key"/>
    <br>
    <input type="file" style="display: none;" id="iFile" onchange="onFileChange(this.files)" />
    文件名: <span id="filename"></span>
    <br>
    <input type="button" value="Decode" onclick="onDecode()" />
    <input type="button" value="Encode" onclick="onEncode()" />
    <br>
</body>

</html>
